<script setup>
import { ElPagination } from 'element-plus';
import index, {useStore} from "vuex";
import { computed, ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from "axios";


let pmArr = ref([])
const user = computed(() => store.state.user)




const store = useStore()
// 来显示搜索框和原数据框的显示和隐藏
let isShow = ref(true);

//搜索关键字
let searchAll = ref("");



// -----------------------------------------

const currentPage = ref(1); // 当前页码 默认是1
const pageSize = ref(5); // 每页显示的条目数  默认是5
const totalItems = computed(()=> pmArr.value.length); // 总条目数，userArr已经初始化
// 当前页的条目数据
const itemsArr = computed(()=> pmArr.value.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value
))
// -----------------------------------------

const handleSizeChange = (s) => {
  pageSize.value = s;
};
const handleCurrentChange = (newPage) => {
  console.log("所要显示的页面:"+newPage);
  currentPage.value = newPage;
};

// -----------------------------------------
const handleCancel = async (id,userId) => {
  const res = await axios.put('consultationAppointment/updateStatusByAppointmentId?appointmentId=' + id + '&status=2')

  if (res.data.code === 200) {
    const title = '取消咨询';
    const content = '咨询师' + user.value.consultantName + '取消了您的预约';
    const url = user.value.consultantAvatar

    await axios.post('notice/insertAll', {
      noticeTitle: title,
      noticeContent: content,
      noticeUrl: url,
      userId: userId
    })


    ElMessage.success('取消咨询');
    await initializeData();
  } else {
    throw new Error('加载失败');
  }


}
const handleComplete = async  (id,userId) => {
  console.log(user);
  const res = await axios.put('consultationAppointment/updateStatusByAppointmentId?appointmentId=' + id + '&status=0')
  if (res.data.code === 200) {
    const title = '完成咨询';
    const content = '您与咨询师' + user.value.consultantName + '完成了咨询';
    const url = user.value.consultantAvatar

    await axios.post('notice/insertAll', {
      noticeTitle: title,
      noticeContent: content,
      noticeUrl: url,
      userId: userId
    })
    ElMessage.success('完成咨询');
    await initializeData();
  } else {
    throw new Error('加载失败');
  }



}
const resetSerchbtn = () => {
  isShow.value = true;
  searchAll.value = "";
}
const serchBtn = () => {
  isShow.value = false;
}

const filterPMArr = computed(() =>
    //filter接受一个回调函数作为参数，并返回一个新数组，该数组包含所有使得回调函数返回true的元素
    pmArr.value.filter(
        (data) =>
            !searchAll.value ||
            String(data.userId).includes(String(searchAll.value)) ||
            data.users.userNickname.toLowerCase().includes(searchAll.value.toLowerCase()) ||
            data.users.userGender.toLowerCase().includes(searchAll.value.toLowerCase()) ||
            data.users.userPhoneNumber.toLowerCase().includes(searchAll.value.toLowerCase()) ||
            data.consultationContent.toLowerCase().includes(searchAll.value.toLowerCase()) ||
            data.appointmentStartTime.toLowerCase().includes(searchAll.value.toLowerCase()) ||
            data.appointmentEndTime.toLowerCase().includes(searchAll.value.toLowerCase())
    )
)

// 封装获取数据的方法
const fetchData = async (consultantId) => {
  try {
    const res = await axios.get('consultationAppointment/selectByConsultantId?consultantId='+consultantId);
    if (res.data.code === 200) {
      console.log('获取到的数据:', res.data.data)
      return res.data.data;
    } else {
      throw new Error('加载失败');
    }
  } catch (error) {
    ElMessage.error(error.message);
    throw error;
  }
};



// 封装初始化数据的方法
const initializeData = async () => {
  const consultantId = user.value.consultantId;
  try {
    pmArr.value = await fetchData(consultantId);
    console.log(pmArr.value);
  } catch (error) {
    // 错误已经在 fetchData 中处理过了
  }
};

// 在组件挂载时调用初始化方法
onMounted(initializeData);
</script>

<template>
  <ul class="xitongYonghu" style="z-index: 1">

    <li class="xitongYonghu-top">

      <ul class="xitong-search" style="padding: 10px;display: flex;justify-content: space-between;align-items: center;">



        <li style="width: 420px">
          <input style="height: 32.5px;width: 250px;box-sizing: border-box;padding: 5px 10px;border-radius: 5px;border: none" type="text" v-model="searchAll">
          <el-button @click="serchBtn" style="margin-left: 10px">
            🔍搜索
          </el-button>
          <el-button @click="resetSerchbtn">
            重置
          </el-button>
        </li>

      </ul>





    </li>
    <li>
      <el-table v-if="isShow" :data="itemsArr" style="width: 99%">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="userId" label="UserId" width="100px" />
        <el-table-column prop="users.userNickname" label="用户昵称" width="100px" />
        <el-table-column prop="users.userGender" label="用户性别" width="100px" />
        <el-table-column prop="users.userPhoneNumber" label="用户手机号" width="120px" />
        <el-table-column prop="consultationContent" label="咨询内容" width="280px" />
        <el-table-column prop="appointmentStartTime" label="咨询开始时间" width="170px" />
        <el-table-column prop="appointmentEndTime" label="咨询结束时间" width="170px" />
        <el-table-column align="right">
          <template #header>
            <p>用户操作</p>
          </template>
          <template #default="scope">
            <el-button size="small"  v-if="scope.row.completionStatus === 0">
              已完成
            </el-button>
            <el-button size="small" @click="handleComplete(scope.row.appointmentId,scope.row.userId)" v-if="scope.row.completionStatus === 1">
              完成咨询
            </el-button>
            <el-button size="small"  v-if="scope.row.completionStatus === 2">
              已取消
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleCancel(scope.row.appointmentId,scope.row.userId)"
                v-if="scope.row.completionStatus === 1"
            >
              取消预约
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-table v-else :data="filterPMArr" style="width: 99%">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="userId" label="UserId" width="100px" />
        <el-table-column prop="users.userNickname" label="用户昵称" width="100px" />
        <el-table-column prop="users.userGender" label="用户性别" width="100px" />
        <el-table-column prop="users.userPhoneNumber" label="用户手机号" width="120px" />
        <el-table-column prop="consultationContent" label="咨询内容" width="280px" />
        <el-table-column prop="appointmentStartTime" label="咨询开始时间" width="170px" />
        <el-table-column prop="appointmentEndTime" label="咨询结束时间" width="170px" />
        <el-table-column align="right">
          <template #header>
            <p>用户操作</p>
          </template>
          <template #default="scope">

            <el-button size="small"  v-if="scope.row.completionStatus === 0">
              已完成
            </el-button>
            <el-button size="small" @click="handleComplete(scope.row.appointmentId,scope.row.userId)" v-if="scope.row.completionStatus === 1">
              完成咨询
            </el-button>
            <el-button size="small"  v-if="scope.row.completionStatus === 2">
              已取消
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleCancel(scope.row.appointmentId,scope.row.userId)"
                v-if="scope.row.completionStatus !== 2"
            >
              取消预约
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </li>
    <li>
      <el-pagination v-if="isShow"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="currentPage"
                     :page-sizes="[3, 5, 10]"
                     :page-size="pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="totalItems">
      </el-pagination>
      <p v-else></p>
    </li>
  </ul>



</template>

<style scoped>
.xitongYonghu{
  width: 99%;
  background-color: #cccccc;
  padding: 15px;
}
.xitongYonghu li{
  width: 100%;
  border-radius: 5px;
}
.xitongYonghu-top {
  background-color: transparent;
  margin-bottom: 10px;
}
.el-pagination{
  margin-top: 10px;
}
</style>